<template>
  <div class="singer">
  <singer-view @selects="selectSinger" :data="singers"></singer-view>
  <router-view></router-view>
  </div>
</template>

<script>
import {getSingerList} from 'api/singer'
import { code } from 'common/js/config'
import Singer from 'common/js/singer'
import SingerView from 'base/singer/singerView'
import {mapMutations} from 'vuex'
const pinyin = require('pinyin')
const HOT_NAME = '热门'
const HOT_SINGERS = 10
export default {
  data() {
    return {
      singers: []
    }
  },
  created() {
    this._getSingerList()
  },
  methods: {
    selectSinger(singers) {
      this.$router.push({
        path: `/singer/${singers.id}`
      })
      this.setSinger(singers)
    },
    _getSingerList() {
      getSingerList().then(res => {
        if (res.data.code === code) {
          let s = res.data.artists
          // 将歌手名字转换成pinyin
          s.map(item => {
            // item.name[0]：歌手名字的首个字
            let py = pinyin(item.name[0], {
              // # 设置拼音风格，第一个字母
              style: pinyin.STYLE_FIRST_LETTER
            })
            item.initial = py[0][0].toUpperCase()
          })
          this.singers = this._normalizeSinger(s)
        }
      })
    },
    _normalizeSinger(list) {
      // 热门
      let map = {
        hot: {
          title: HOT_NAME,
          item: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGERS) {
          map.hot.item.push(new Singer({
            id: item.id,
            name: item.name,
            avatar: item.img1v1Url,
            aliaName: item.alias.join(' / ')
          }))
        }
        // 按首字母大写查
        /**
          map = {
            hot: {}
            A,
            B
            ......
         */
        const key = item.initial
        if (!map[key]) {
          map[key] = {
            title: key,
            item: []
          }
        }
        map[key].item.push(new Singer({
          id: item.id,
          name: item.name,
          avatar: item.img1v1Url,
          aliaName: item.alias[0]
        }))
      })
      /**
      *上面的map是对象，不能进行有序列表，
      *将map对象转换成数组，为有序列表做准备
      */
      let hot = []
      let ret = []
      for (const key in map) {
        let val = map[key]
        if (val.title.match(/[A-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      // 将数组里面的值，按照a-z顺序排列
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      // 我们创建了两个数组，然后使用 concat() 把它们连接起来：
      return hot.concat(ret)
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  components: {
    SingerView
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~common/stylus/variable'
.singer
  position: fixed
  top: 80px
  bottom:0
  width:100%
</style>